# -*- coding: utf-8 -*-
"""
Created on Thu Nov 25 20:15:05 2021

@author: bwm
"""
import pandas as pd
class porfolio:
    #初始化现金、总市值、股票持仓、股票价值
    def __init__(self, cash, date,commission, my_history,find):
        #当前现金
        self.cash = cash
        #当前总市值
        self.total_value = cash
        #当前持仓信息，一个dateframe，横坐标是股票代码，纵坐标是数量num和价格price
        self.stock_hold = pd.DataFrame(columns=['num', 'price'],index = []) 
        #当前股票价值
        self.stock_value = 0
        self.date = date
        self.commission = commission
        self.my_history = my_history
        self.find = find
        
	#卖出所有持仓股票
    def sell_all(self,date):
        stock_in_stock_hold = self.stock_hold.index.tolist()#获取当前所有持仓股票代码
        if len(stock_in_stock_hold)>0:
            for i in stock_in_stock_hold:
                self.sell(i, self.stock_hold.loc[i]['num'],date)
                
	#买股票
    def buy(self,stock,num,date):
        price = self.find.get_data(date,stock,'收盘价')#获取相应股票的价格
        self.cash = self.cash - price*num - price*num*self.commission
        self.stock_hold.loc[stock] = {'num':num,'price':price}#记录持仓
        self.stock_value = sum(self.stock_hold['num']*self.stock_hold['price'])
        self.total_value = self.cash + self.stock_value
        self.my_history.order_history.append([date,stock, num ,price,'买'])
	
    #卖股票
    def sell(self,stock,num,date):
        price = self.find.get_data(date,stock,'收盘价')
        self.cash = self.cash + price*num - price*num*self.commission
        self.stock_hold.drop(index = stock, inplace = True)####此处有个问题是，会直接卖掉这个股票全部，不过可以忽略，由于不考虑交易成本，大不了卖了再买
        self.stock_value = sum(self.stock_hold['num']*self.stock_hold['price'])
        self.total_value = self.cash + self.stock_value
        self.my_history.order_history.append([date,stock,num,price,'卖'])
        